package com.nhjf.mobile.controller.user;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.net.SyslogAppender;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.code.kaptcha.Producer;
import com.nhjf.command.student.CreateStudentCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.common.util.Encrypt;
import com.nhjf.common.util.IPTool;
import com.nhjf.common.util.MD5;
import com.nhjf.mobile.common.util.AlipayConfig;
import com.nhjf.mobile.common.util.SignUtil;
import com.nhjf.mobile.common.util.SignatureUtil;
import com.nhjf.mobile.common.util.SysProperties;
import com.nhjf.mobile.common.util.WebUtils;
import com.nhjf.mobile.common.util.WeixinConfig;
import com.nhjf.mobile.common.util.XmlUtils;
import com.nhjf.mobile.controller.BaseController;
import com.nhjf.model.coursesSeries.CoursesSeries;
import com.nhjf.model.incomeAndExpenditureRecord.IncomeAndExpenditureRecordd;
import com.nhjf.model.payLog.PayLog;
import com.nhjf.model.sms.SmsSendLog;
import com.nhjf.model.student.Student;
import com.nhjf.model.system.AdminSession;
import com.nhjf.model.system.Resource;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.pojo.dto.result.ServiceResultDto;
import com.nhjf.pojo.dto.teachers.teachersResultDto;
import com.nhjf.pojo.qo.payLog.PayLogQo;
import com.nhjf.pojo.qo.sms.SmsSendLogQo;
import com.nhjf.pojo.qo.studnet.StudentQo;
import com.nhjf.pojo.qo.system.AdminSessionQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.coursesSeries.CoursesSeriesService;
import com.nhjf.service.incomeAndExpenditureRecordd.IncomeAndExpenditureRecorddService;
import com.nhjf.service.payLog.PayLogService;
import com.nhjf.service.sms.SmsSendLogService;
import com.nhjf.service.student.StudentService;
import com.nhjf.service.system.AdminSessionService;
import com.nhjf.service.system.ResourceService;
import com.nhjf.service.system.RoleService;
import com.nhjf.service.system.UserService;
import com.nhjf.service.teachers.TeachersService;

import net.sf.json.JSONObject;

/**
 * @类功能说明：用户管理
 * @部门：技术部
 * @作者：龚一凡
 * @版本：V1.0
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController{
	@Autowired
	private SmsSendLogService smsSendLogService;
	@Autowired
	private UserService userService;
	@Autowired
	private AdminSessionService adminSessionService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private TeachersService teacherService;
	@Autowired
	private CoursesSeriesService coursesSeriesService;
	@Autowired
	private PayLogService payLogService;
	@Autowired
	private IncomeAndExpenditureRecorddService andExpenditureRecorddService;
	@Autowired
	private Producer captchaProducer;
	private ExecutorService executorService = Executors.newFixedThreadPool(20);
	private static final String LM_SESSION_VALID_CODE_KEY = "_LM_SESSION_VALID_CODE_";
	//产品名称:云通信短信API产品,开发者无需替换
	static final String product = "Dysmsapi";
	//产品域名,开发者无需替换
	static final String domain = "dysmsapi.aliyuncs.com";
	//短信模板-注册验证码
	static final String TemplateCode1 = "SMS_147416051";
	//短信模板-重置密码验证码
	static final String TemplateCode2 = "SMS_147416056";

	// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
	static final String accessKeyId = "LTAI9vcgF91f6sk7";
	static final String accessKeySecret = "e41ufzOmhPU079xAI4kZX87Mht0QW8";
	//API密钥baize41ufzOmhP329xAI4kZX87Mht0d3
	//    static final String secretKey = "79xAI4kZX87Mht";

	static String salts="xHellxo110xadmin";
	/**
	 * openId请求URL
	 */
	private static final String OPEN_ID_REQUEST_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	/**
	 * prepay_id请求URL
	 */
	private static final String PREPAY_ID_REQUEST_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	/**
	 * 查询订单请求URL
	 */
	private static final String ORDER_QUERY_REQUEST_URL = "https://api.mch.weixin.qq.com/pay/orderquery";
	/**
	 * 获取access_token
	 */
	private static final String access_token_url = "https://api.weixin.qq.com/cgi-bin/token";
	/**
	 * 获取jsapi_ticket
	 */
	private static final String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";

	//微信支付接口固定值
	//公众号id
	static final String appid = "wx2aec8d2e0a62811f";
	//商户号
	static final String mch_id = "1520871871";
	//设备号
	static final String device_info = "WEB";
	//开发者密码
	static final String AppSecret = "09b8ee0139256ea160bd944123b1e88c";
	static final String ApiKey="baize41ufzOmhP329xAI4kZX87Mht0d3";


	/**
	 * 
	 * @方法功能说明：登陆校验
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value="/check")
	public String loginCheck(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value="loginName", required=false) String loginName,
			@RequestParam(value = "password", required = false) String password,
			@RequestParam(value = "secretKey", required = false) String secretKey) {

		String code  =  "500";

		Map<String, Object> resMap=new HashMap<String, Object>();
		if(StringUtils.isEmpty(secretKey)||!SignUtil.secretKey.equals(secretKey)) {
			resMap.put("code", "500");
			resMap.put("message", "非法请求");
			return JSONObject.fromObject(resMap).toString();
		}else {
			if (StringUtils.isEmpty(loginName)) {
				resMap.put("code", "500");
				resMap.put("message", "登录名为空");
				return JSONObject.fromObject(resMap).toString();
			}
			//判断用户名是否包含除字母数字的其他字符
			boolean b = Pattern.matches("^[0-9]+$", loginName);
			if(!b){
				resMap.put("code", "500");
				resMap.put("message", "登录名只能是手机号");
				return JSONObject.fromObject(resMap).toString();
			}
			if(loginName != null && loginName.length()!=11){
				resMap.put("code", "500");
				resMap.put("message", "登录名只能是手机号");
				return JSONObject.fromObject(resMap).toString();
			}
			if (StringUtils.isEmpty(password)) {
				resMap.put("code", "500");
				resMap.put("message", "密码为空");
				return JSONObject.fromObject(resMap).toString();
			}
			UserQo qo=new UserQo();
			qo.setUserName(loginName);
			qo.setSeachRole(true);
			qo.setItsusableornot(1);
			User user=userService.queryUnique(qo);
			Encrypt encrypt=new Encrypt();
			if(user!=null){
				if(user.getUserPassword()!=null) {
					String sha256PassWord=encrypt.SHA256(user.getUserPassword()+salts);
					//    		    		if(sha256PassWord.equals(password)) {
					if(password.equals(user.getUserPassword())) {

					}else {
						resMap.put("code", "500");
						resMap.put("message", "账号密码错误");
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "500");
					resMap.put("message", "账号异常");
					return JSONObject.fromObject(resMap).toString();
				}
			}else {
				resMap.put("code", "500");
				resMap.put("message", "账号密码错误");
				return JSONObject.fromObject(resMap).toString();
			}

			Set<Role> uRoles = user.getRoleList();

			Iterator<Role> iter = uRoles.iterator();
			Role role=new Role();
			while(iter.hasNext()) {
				role=iter.next();
				break;
			}
			if(role==null||role.getId()==1L) {
				resMap.put("code", "500");
				resMap.put("message", "只有老师和学生账号才能登陆！");
				return JSONObject.fromObject(resMap).toString();
			}
			AdminSession entityadminSession=new AdminSession();
			entityadminSession.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			entityadminSession.setLoginName(loginName);
			String adminSessiontoken=salts;
			adminSessiontoken+="@#"+loginName;
			Date todayTime=new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd");
			SimpleDateFormat dateFormat1 = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			adminSessiontoken+="@#"+dateFormat.format(todayTime);
			String ipaddress=IPTool.getInstance().getIpAddr(request);
			adminSessiontoken+="@#"+ipaddress;
			Calendar c = Calendar.getInstance();  
			c.setTime(todayTime); 
			c.add(Calendar.MINUTE,45 );
			entityadminSession.setToken(MD5.MD5Encode(adminSessiontoken));
			entityadminSession.setExpiryTime(c.getTime());
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setLoginName(loginName);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				entityadminSession.setId(adminSession.getId());
				adminSessionService.update(entityadminSession);
			}else {
				adminSessionService.save(entityadminSession);
			}
			Map<String, String> userMap=new HashMap<String, String>();
			TeachersQo teacherQo=new TeachersQo();
			teacherQo.setUserId(user.getId());
			Teacher teacher=teacherService.queryUnique(teacherQo);
			SysProperties sysProperties=SysProperties.getInstance();
			String imagePath=sysProperties.get("commentImagePath");
			if(teacher!=null) {
				userMap.put("token", MD5.MD5Encode(adminSessiontoken));
				userMap.put("nikeName", teacher.getNickname());
				userMap.put("avatar", teacher.getAvatar()==null?"":imagePath+"/picture/"+teacher.getAvatar());
				userMap.put("isRole", "2");
				resMap.put("message", userMap);
				resMap.put("code", "200");
			}else {
				StudentQo studentQo=new StudentQo();
				studentQo.setUserid(user.getId());
				Student student=studentService.queryUnique(studentQo);
				if(student!=null) {
					userMap.put("token", MD5.MD5Encode(adminSessiontoken));
					userMap.put("nikeName", student.getNickname());
					userMap.put("avatar", student.getAvatar()==null?"":imagePath+"/picture/"+student.getAvatar());
					userMap.put("isRole", "1");
					resMap.put("message", userMap);
					resMap.put("code", "200");
				}else {
					resMap.put("message", "账号出错");
					resMap.put("code", "500");
				}
			}



		}

		return JSONObject.fromObject(resMap).toString();
	}
	/**
	 * 
	 * @方法功能说明：登陆校验
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value="/loginAdminCheck")
	public String loginAdminCheck(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value="loginName", required=false) String loginName,
			@RequestParam(value = "password", required = false) String password,
			@RequestParam(value = "secretKey", required = false) String secretKey,
			@RequestParam(value = "validcode", required = false) String validcode) {

		String code  =  "500";

		Map<String, Object> resMap=new HashMap<String, Object>();
		if(StringUtils.isEmpty(secretKey)||!SignUtil.secretKey.equals(secretKey)) {
			resMap.put("code", "500");
			resMap.put("message", "非法请求");
			return JSONObject.fromObject(resMap).toString();
		}else {
			if (StringUtils.isEmpty(loginName)) {
				resMap.put("code", "500");
				resMap.put("message", "登录名为空");
				return JSONObject.fromObject(resMap).toString();
			}
			//判断用户名是否包含除字母数字的其他字符
			boolean b = Pattern.matches("^[0-9]+$", loginName);
			if (StringUtils.isEmpty(password)) {
				resMap.put("code", "500");
				resMap.put("message", "密码为空");
				return JSONObject.fromObject(resMap).toString();
			}
			//			if(validCodeCheck(request, validcode)) {
			//				
			//			}else {
			//				resMap.put("code", "500");
			//				resMap.put("message", "验证码错误!");
			//				return JSONObject.fromObject(resMap).toString();
			//			}
			UserQo qo=new UserQo();
			qo.setUserName(loginName);
			qo.setSeachRole(true);
			qo.setItsusableornot(1);
			User user=userService.queryUnique(qo);
			Encrypt encrypt=new Encrypt();
			if(user!=null){
				if(user.getUserPassword()!=null) {
					String sha256PassWord=encrypt.SHA256(user.getUserPassword()+salts);
					//    		    		if(sha256PassWord.equals(password)) {
					if(password.equals(user.getUserPassword())) {

					}else {
						resMap.put("code", "500");
						resMap.put("message", "账号密码错误");
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "500");
					resMap.put("message", "账号异常");
					return JSONObject.fromObject(resMap).toString();
				}
			}else {
				resMap.put("code", "500");
				resMap.put("message", "账号密码错误");
				return JSONObject.fromObject(resMap).toString();
			}

			Set<Role> uRoles = user.getRoleList();

			Iterator<Role> iter = uRoles.iterator();
			Role role=new Role();
			while(iter.hasNext()) {
				role=iter.next();
				break;
			}
			if(role==null||role.getId()==1L ||role.getId()==4L) {
				resMap.put("code", "500");
				resMap.put("message", "只有老师才能登陆！");
				return JSONObject.fromObject(resMap).toString();
			}
			AdminSession entityadminSession=new AdminSession();
			entityadminSession.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			entityadminSession.setLoginName(loginName);
			String adminSessiontoken=salts;
			adminSessiontoken+="@#"+loginName;
			Date todayTime=new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd");
			SimpleDateFormat dateFormat1 = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			adminSessiontoken+="@#"+dateFormat.format(todayTime);
			String ipaddress=IPTool.getInstance().getIpAddr(request);
			adminSessiontoken+="@#"+ipaddress;
			Calendar c = Calendar.getInstance();  
			c.setTime(todayTime); 
			c.add(Calendar.MINUTE,45 );
			entityadminSession.setToken(MD5.MD5Encode(adminSessiontoken));
			entityadminSession.setExpiryTime(c.getTime());
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setLoginName(loginName);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				entityadminSession.setId(adminSession.getId());
				adminSessionService.update(entityadminSession);
			}else {
				adminSessionService.save(entityadminSession);
			}
			Map<String, String> userMap=new HashMap<String, String>();
			TeachersQo teacherQo=new TeachersQo();
			teacherQo.setUserId(user.getId());
			Teacher teacher=teacherService.queryUnique(teacherQo);
			SysProperties sysProperties=SysProperties.getInstance();
			String imagePath=sysProperties.get("commentImagePath");
			if(teacher!=null) {
				if(role.getId()==2L) {
					userMap.put("isRole", "3");//机构管理员
				}else {
					userMap.put("isRole", "2");//老师
				}
				userMap.put("token", MD5.MD5Encode(adminSessiontoken));
				userMap.put("nikeName", teacher.getNickname());
				userMap.put("avatar", teacher.getAvatar()==null?"":imagePath+"/picture/"+teacher.getAvatar());
				resMap.put("message", userMap);
				resMap.put("code", "200");
			}else {
				resMap.put("message", "账号出错");
				resMap.put("code", "500");
			}



		}

		return JSONObject.fromObject(resMap).toString();
	}
	//	 /**
	//    *
	//    * @方法功能说明：验证码生成
	//    * @修改时间：2017-07-25 20:34:47
	//    * @修改内容：
	//    * @参数：
	//    * @return:
	//    * @throws
	//    */
	//   @RequestMapping(value="/valid-code-image.jpg")
	//   public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
	//       HttpSession session = request.getSession();
	//       response.setDateHeader("Expires", 0);
	//       response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	//       response.addHeader("Cache-Control", "post-check=0, pre-check=0");
	//       response.setHeader("Pragma", "no-cache");
	//       response.setContentType("image/jpeg");
	//       // 生成验证码
	//       String capText = captchaProducer.createText();
	//       session.setAttribute(LM_SESSION_VALID_CODE_KEY, capText);
	//       BufferedImage bi = captchaProducer.createImage(capText);
	//       ServletOutputStream out = null;
	//       try {
	//           out = response.getOutputStream();
	//           ImageIO.write(bi, "jpg", out);
	//           out.flush();
	//       } finally {
	//           if (out != null) {
	//				out.close();
	//			}
	//       }
	//   }
	//   /**
	//   *
	//   * @方法功能说明：校验验证码
	//   * @修改内容：
	//   * @参数：@param request
	//   * @参数：@param validCode
	//   * @参数：@return
	//   * @return:boolean
	//   * @throws
	//   */
	//  protected boolean validCodeCheck(HttpServletRequest request, String validCode) {
	//      if (validCode == null) {
	//			return false;
	//		}
	//
	//      String sessionValidCode = (String) request.getSession().getAttribute(LM_SESSION_VALID_CODE_KEY);
	//      request.getSession().removeAttribute(LM_SESSION_VALID_CODE_KEY);
	//
	//      if (sessionValidCode == null) {
	//			return false;
	//		}
	//
	//      // 匹配验证码
	//      if (StringUtils.equalsIgnoreCase(validCode, sessionValidCode)) {
	//			return true;
	//		}
	//
	//      return false;
	//  }
	/**
	 * 
	 * @方法功能说明：注册
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value="/register")
	public String register(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value="loginName", required=true) String loginName,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "code", required = true) String code,
			@RequestParam(value = "secretKey", required = true) String secretKey){


		Map<String, String> resMap=new HashMap<String, String>();
		if(StringUtils.isEmpty(secretKey)||!SignUtil.secretKey.equals(secretKey)) {
			resMap.put("code", "500");
			resMap.put("message", "非法请求");
			return JSONObject.fromObject(resMap).toString();
		}else {
			if(StringUtils.isEmpty(loginName)) {
				resMap.put("code", "500");
				resMap.put("message", "电话号为空");
				return JSONObject.fromObject(resMap).toString();
			}
			//判断用户名是否包含除字母数字的其他字符
			boolean b = Pattern.matches("^[0-9]+$", loginName);
			if(!b){
				resMap.put("code", "500");
				resMap.put("message", "登录名只能是手机号");
				return JSONObject.fromObject(resMap).toString();
			}
			if(loginName != null && loginName.length()!=11){
				resMap.put("code", "500");
				resMap.put("message", "登录名只能是手机号");
				return JSONObject.fromObject(resMap).toString();
			}
			if (StringUtils.isEmpty(password)) {
				resMap.put("code", "500");
				resMap.put("message", "密码为空");
				return JSONObject.fromObject(resMap).toString();
			}
			UserQo qo=new UserQo();
			qo.setUserName(loginName);
			User user=userService.queryUnique(qo);
			if(user!=null) {
				resMap.put("code", "500");
				resMap.put("message", "该账号已存在");
				return JSONObject.fromObject(resMap).toString();
			}
			SmsSendLogQo smsSendLogQo=new SmsSendLogQo();
			Calendar beforeTime = Calendar.getInstance();
			beforeTime.add(Calendar.MINUTE, -5);// 5分钟之前的时间
			Date beforeD = beforeTime.getTime();
			smsSendLogQo.setSendTime(beforeD);
			smsSendLogQo.setType(1);
			SmsSendLog smsSendLog=smsSendLogService.queryUnique(smsSendLogQo);
			if(smsSendLog==null) {
				resMap.put("code", "500");
				resMap.put("message", "验证码失效");
				return JSONObject.fromObject(resMap).toString();
			}
			if(!code.equals(smsSendLog.getCode())) {
				resMap.put("code", "500");
				resMap.put("message", "验证码错误");
				return JSONObject.fromObject(resMap).toString();
			}
			CreateStudentCommand createStudentCommand=new CreateStudentCommand();
			createStudentCommand.setUserName(loginName);
			//    	    Encrypt encrypt=new Encrypt();
			//    	    String sha256PassWord=encrypt.SHA256(MD5.MD5Encode(user.getUserPassword())+salts);
			createStudentCommand.setUserPassword(password);
			ServiceResultDto serviceResultDto=studentService.createStudent(createStudentCommand);
			if(serviceResultDto.getSuccess()) {
				resMap.put("code", "200");
				resMap.put("message", "注册成功");
				return JSONObject.fromObject(resMap).toString();
			}else {
				resMap.put("code", "500");
				resMap.put("message", "系统错误");
				return JSONObject.fromObject(resMap).toString();
			}
		}
	}
	/**
	 * 
	 * @方法功能说明：重置密码
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value="/resetPassword")
	public String resetPassword(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value="loginName", required=true) String loginName,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "newPassword", required = true) String newPassword,
			@RequestParam(value = "code", required = true) String code,
			@RequestParam(value = "secretKey", required = true) String secretKey){

		Map<String, String> resMap=new HashMap<String, String>();
		if(StringUtils.isEmpty(secretKey)||!SignUtil.secretKey.equals(secretKey)) {
			resMap.put("code", "500");
			resMap.put("message", "非法请求");
			return JSONObject.fromObject(resMap).toString();
		}else {
			if(StringUtils.isEmpty(loginName)) {
				resMap.put("code", "500");
				resMap.put("message", "电话号为空");
				return JSONObject.fromObject(resMap).toString();
			}
			//判断用户名是否包含除字母数字的其他字符
			boolean b = Pattern.matches("^[0-9]+$", loginName);
			if(!b){
				resMap.put("code", "500");
				resMap.put("message", "登录名只能是手机号");
				return JSONObject.fromObject(resMap).toString();
			}
			if(loginName != null && loginName.length()!=11){
				resMap.put("code", "500");
				resMap.put("message", "登录名只能是手机号");
				return JSONObject.fromObject(resMap).toString();
			}
			if (StringUtils.isEmpty(password)||StringUtils.isEmpty(newPassword)) {
				resMap.put("code", "500");
				resMap.put("message", "密码为空");
				return JSONObject.fromObject(resMap).toString();
			}
			if (!password.equals(newPassword)) {
				resMap.put("code", "500");
				resMap.put("message", "两次密码不一样");
				return JSONObject.fromObject(resMap).toString();
			}
			SmsSendLogQo smsSendLogQo=new SmsSendLogQo();
			Calendar beforeTime = Calendar.getInstance();
			beforeTime.add(Calendar.MINUTE, -5);// 5分钟之前的时间
			Date beforeD = beforeTime.getTime();
			smsSendLogQo.setSendTime(beforeD);
			smsSendLogQo.setType(2);
			SmsSendLog smsSendLog=smsSendLogService.queryUnique(smsSendLogQo);
			if(smsSendLog==null) {
				resMap.put("code", "500");
				resMap.put("message", "验证码失效");
				return JSONObject.fromObject(resMap).toString();
			}
			if(!code.equals(smsSendLog.getCode())) {
				resMap.put("code", "500");
				resMap.put("message", "验证码错误");
				return JSONObject.fromObject(resMap).toString();
			}
			UserQo qo=new UserQo();
			qo.setUserName(loginName);
			qo.setSeachRole(true);
			User user=userService.queryUnique(qo);
			if(user==null) {
				resMap.put("code", "500");
				resMap.put("message", "用户未注册");
				return JSONObject.fromObject(resMap).toString();
			}
			user.setUserPassword(password);
			userService.update(user);
			resMap.put("code", "200");
			resMap.put("message", "重置密码成功");
			return JSONObject.fromObject(resMap).toString();
		}

	}
	@RequestMapping(value = "/test")
	public void test(){
		SmsSendLogQo smsSendLogQo=new SmsSendLogQo();
		Calendar beforeTime = Calendar.getInstance();
		beforeTime.add(Calendar.MINUTE, -5);// 3分钟之前的时间
		Date beforeD = beforeTime.getTime();
		smsSendLogQo.setSendTime(beforeD);
		smsSendLogQo.setType(1);
		smsSendLogQo.setPhoneNumber("13726028849");
		SmsSendLog smsSendLog=smsSendLogService.queryUnique(smsSendLogQo);
		System.out.println("ok");
	}

	/**
	 * 
	 * @方法功能说明：用户注册发送验证码
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/sendCode")
	public String sendCode(HttpServletRequest request, Model model,String phoneNumber){
		Map<String, String> resMap=new HashMap<String, String>();
		if(StringUtils.isEmpty(phoneNumber)) {
			resMap.put("code", "500");
			resMap.put("message", "手机号为空");
			return JSONObject.fromObject(resMap).toString();
		}
		if(!StringUtils.isEmpty(phoneNumber)&&isMobileNO(phoneNumber)) {

		}else {
			resMap.put("code", "500");
			resMap.put("message", "请填写正确的手机号");
			return JSONObject.fromObject(resMap).toString();
		}
		SmsSendLogQo smsSendLogQo=new SmsSendLogQo();
		Calendar beforeTime = Calendar.getInstance();
		beforeTime.add(Calendar.MINUTE, -1);// 1分钟之前的时间
		Date beforeD = beforeTime.getTime();
		smsSendLogQo.setSendTime(beforeD);
		smsSendLogQo.setType(1);
		SmsSendLog smsSendLogs=smsSendLogService.queryUnique(smsSendLogQo);
		if(smsSendLogs!=null) {
			resMap.put("code", "500");
			resMap.put("message", "发送验证码太频繁");
			return JSONObject.fromObject(resMap).toString();
		}
		// 生成验证码
		String capText = getFourRandom();

		//发短信
		SendSmsResponse response = sendSms(capText, phoneNumber, 1);
		SmsSendLog smsSendLog=new SmsSendLog();
		smsSendLog.setCode(capText);
		smsSendLog.setPhoneNumber(phoneNumber);
		smsSendLog.setSendSmsResponseCode(response.getCode());
		smsSendLog.setSendSmsResponseMessage(response.getMessage());
		smsSendLog.setSendTime(new Date());
		smsSendLog.setType(1);
		smsSendLogService.save(smsSendLog);
		if(response.getCode() != null && response.getCode().equals("OK")) {
			//            System.out.println("短信接口返回的数据----------------");
			//            System.out.println("Code=" + response.getCode());
			//            System.out.println("Message=" + response.getMessage());
			//            System.out.println("RequestId=" + response.getRequestId());
			//            System.out.println("BizId=" + response.getBizId());
			resMap.put("code", "200");
			resMap.put("message", response.getMessage());
		}else {
			resMap.put("code", "500");
			resMap.put("message", response.getMessage());
		}
		return JSONObject.fromObject(resMap).toString();
	}	
	/**
	 * 
	 * @方法功能说明：用户重置密码发送验证码
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/sendResetCode")
	public String sendResetCode(HttpServletRequest request, Model model,String phoneNumber){
		Map<String, String> resMap=new HashMap<String, String>();
		if(StringUtils.isEmpty(phoneNumber)) {
			resMap.put("code", "500");
			resMap.put("message", "手机号为空");
			return JSONObject.fromObject(resMap).toString();
		}
		SmsSendLogQo smsSendLogQo=new SmsSendLogQo();
		Calendar beforeTime = Calendar.getInstance();
		beforeTime.add(Calendar.MINUTE, -1);// 1分钟之前的时间
		Date beforeD = beforeTime.getTime();
		smsSendLogQo.setSendTime(beforeD);
		smsSendLogQo.setType(2);
		SmsSendLog smsSendLogs=smsSendLogService.queryUnique(smsSendLogQo);
		if(smsSendLogs!=null) {
			resMap.put("code", "500");
			resMap.put("message", "发送验证码太频繁");
			return JSONObject.fromObject(resMap).toString();
		}
		if(!StringUtils.isEmpty(phoneNumber)&&isMobileNO(phoneNumber)) {

		}else {
			resMap.put("code", "500");
			resMap.put("message", "请填写正确的手机号");
			return JSONObject.fromObject(resMap).toString();
		}
		if(!isMobileNO(phoneNumber)) {
			resMap.put("code", "500");
			resMap.put("message", "请填写正确的手机号");
			return JSONObject.fromObject(resMap).toString();
		}
		// 生成验证码
		String capText = getFourRandom();

		//发短信
		SendSmsResponse response = sendSms(capText, phoneNumber, 2);
		SmsSendLog smsSendLog=new SmsSendLog();
		smsSendLog.setCode(capText);
		smsSendLog.setPhoneNumber(phoneNumber);
		smsSendLog.setSendSmsResponseCode(response.getCode());
		smsSendLog.setSendSmsResponseMessage(response.getMessage());
		smsSendLog.setSendTime(new Date());
		smsSendLog.setType(2);
		smsSendLogService.save(smsSendLog);
		if(response.getCode() != null && response.getCode().equals("OK")) {
			resMap.put("code", "200");
			resMap.put("message", response.getMessage());
		}else {
			resMap.put("code", "500");
			resMap.put("message", response.getMessage());
		}
		return JSONObject.fromObject(resMap).toString();
	}


	/**
	 * 
	 * @方法功能说明：微信网页支付
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/pay")
	public String payHandle(@RequestParam(value="token", required=true)String  token,String code, HttpServletRequest request, HttpServletResponse response,String coursesSeriesId,String ip) throws Exception {
		Map<String, String> resMap=new HashMap<String, String>();

		if (StringUtils.isEmpty(code)) {
			resMap.put("code", "500");
			resMap.put("message", "code不能为空");
		}
		AdminSession adminSession=new AdminSession();
		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession==null) {
			resMap.put("code", "406");
			resMap.put("message", "不存在此账号！");
			return JSONObject.fromObject(resMap).toString();
		}else {
			adminSession.getLoginName();
			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user==null) {
				resMap.put("code", "406");
				resMap.put("message", "未登录!");
				return JSONObject.fromObject(resMap).toString();
			}else {
				String openId = getOpenId(code);
				CoursesSeries coursesSeries=coursesSeriesService.get(Long.parseLong(coursesSeriesId));
				if(coursesSeries==null){
					resMap.put("code", "500");
					resMap.put("message", "课程为空!");
					return JSONObject.fromObject(resMap).toString();
				}
				PayLogQo payLogQo=new PayLogQo();
				payLogQo.setUser(user.getId());
				payLogQo.setCoursesSeries(Long.parseLong(coursesSeriesId));
				payLogQo.setStatus(2);
				PayLog payLog=payLogService.queryUnique(payLogQo);
				if(payLog!=null){
					resMap.put("code", "500");
					resMap.put("message", "课程已购买!");
					return JSONObject.fromObject(resMap).toString();
				}
				Map<String, Object> parameterMap = new TreeMap<>();
				parameterMap.put("appid", appid);
				parameterMap.put("mch_id", mch_id);
				parameterMap.put("nonce_str", DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30)));
				parameterMap.put("body", StringUtils.abbreviate(coursesSeries.getTotalTitle().replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5 ]", ""), 600));
				String uuid=UUID.randomUUID().toString().replaceAll("-", "");
				//				String url=request.getServerName()+request.getRequestURI() ;
				parameterMap.put("total_fee", coursesSeries.getPrice());
				parameterMap.put("spbill_create_ip", ip);

				PayLog entity=new PayLog();
				entity.setParameters(JSONObject.fromObject(parameterMap).toString());
				entity.setPayType(1);
				entity.setStatus(1);
				entity.setMoney(coursesSeries.getPrice());
				entity.setCoursesSeries(coursesSeries);
				entity.setCreateTime(new Date());
				entity.setUser(user);
				entity=payLogService.save(entity);
				parameterMap.put("out_trade_no", entity.getId());
				parameterMap.put("notify_url", "http://www.baizeyikao.cn/webMobile/user/payResult/"+entity.getId());
				parameterMap.put("trade_type", "JSAPI");
				parameterMap.put("openid", openId);
				parameterMap.put("sign", generateSign(parameterMap));
				//				resMap.put("code", "500");
				//				resMap.put("message", "课程为空!");
				//				return JSONObject.fromObject(parameterMap).toString();
				String result = WebUtils.post(PREPAY_ID_REQUEST_URL, XmlUtils.toXml(parameterMap));
				Map<String, String> resultMap = XmlUtils.toObject(result, new TypeReference<Map<String, String>>() {
				});

				String prepayId = resultMap.get("prepay_id");
				String tradeType = resultMap.get("trade_type");
				String resultCode = resultMap.get("result_code");

				if (StringUtils.equals(tradeType, "JSAPI") && StringUtils.equals(resultCode, "SUCCESS")) {
					Map<String, Object> modelMap = new TreeMap<>();
					modelMap.put("appId", appid);
					//					modelMap.put("timeStamp", new Date().getTime());
					//					modelMap.put("nonceStr", DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30)));
					modelMap.put("prepayId", prepayId);
					modelMap.put("orderId", entity.getId());
					//					modelMap.put("signType", "MD5");
					//					modelMap.put("paySign", generateSign(modelMap));
					//					modelMap.put("postPayUrl", getPostPayUrl(paymentPlugin, paymentTransaction));
					//					modelAndView.addAllObjects(modelMap);
					//					modelAndView.setViewName("net/shopxx/plugin/weixinPublicPayment/pay");
					resMap.put("code", "200");
					resMap.put("message", JSONObject.fromObject(modelMap).toString());
					return JSONObject.fromObject(resMap).toString();
				}else{
					resMap.put("code", "500");
					resMap.put("message", JSONObject.fromObject(resultMap).toString());
					return JSONObject.fromObject(resMap).toString();
				}
			}
		}

	}
	/**
	 * 
	 * @方法功能说明：微信APP支付
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/appPay")
	public String appPay(@RequestParam(value="token", required=true)String  token, HttpServletRequest request, HttpServletResponse response,String coursesSeriesId,String ip) throws Exception {
		Map<String, String> resMap=new HashMap<String, String>();


		AdminSession adminSession=new AdminSession();
		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession==null) {
			resMap.put("code", "406");
			resMap.put("message", "不存在此账号！");
			return JSONObject.fromObject(resMap).toString();
		}else {
			adminSession.getLoginName();
			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user==null) {
				resMap.put("code", "406");
				resMap.put("message", "未登录!");
				return JSONObject.fromObject(resMap).toString();
			}else {

				CoursesSeries coursesSeries=coursesSeriesService.get(Long.parseLong(coursesSeriesId));
				if(coursesSeries==null){
					resMap.put("code", "500");
					resMap.put("message", "课程为空!");
					return JSONObject.fromObject(resMap).toString();
				}
				PayLogQo payLogQo=new PayLogQo();
				payLogQo.setUser(user.getId());
				payLogQo.setCoursesSeries(Long.parseLong(coursesSeriesId));
				payLogQo.setStatus(2);
				PayLog payLog=payLogService.queryUnique(payLogQo);
				if(payLog!=null){
					resMap.put("code", "500");
					resMap.put("message", "课程已购买!");
					return JSONObject.fromObject(resMap).toString();
				}
				Map<String, Object> parameterMap = new TreeMap<>();
				parameterMap.put("appid", AlipayConfig.APP_ID);
				parameterMap.put("mch_id", AlipayConfig.MCH_ID);
				parameterMap.put("nonce_str", DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30)));
				parameterMap.put("body", StringUtils.abbreviate(coursesSeries.getTotalTitle().replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5 ]", ""), 600));
				String uuid=UUID.randomUUID().toString().replaceAll("-", "");
				//				String url=request.getServerName()+request.getRequestURI() ;
				parameterMap.put("total_fee", coursesSeries.getPrice());
				parameterMap.put("spbill_create_ip", ip);

				PayLog entity=new PayLog();
				entity.setParameters(JSONObject.fromObject(parameterMap).toString());
				entity.setPayType(1);
				entity.setStatus(1);
				entity.setMoney(coursesSeries.getPrice());
				entity.setCoursesSeries(coursesSeries);
				entity.setCreateTime(new Date());
				entity.setUser(user);
				entity=payLogService.save(entity);
				parameterMap.put("out_trade_no", entity.getId());
				parameterMap.put("notify_url", "http://www.baizeyikao.cn/webMobile/user/payNotifyUrl");
				parameterMap.put("trade_type", "APP");
				parameterMap.put("sign", generateSign(parameterMap));
				//				resMap.put("code", "500");
				//				resMap.put("message", "课程为空!");
				//				return JSONObject.fromObject(parameterMap).toString();
				String result = WebUtils.post(PREPAY_ID_REQUEST_URL, XmlUtils.toXml(parameterMap));
				Map<String, String> resultMap = XmlUtils.toObject(result, new TypeReference<Map<String, String>>() {
				});

				String prepayId = resultMap.get("prepay_id");
				String tradeType = resultMap.get("trade_type");
				String resultCode = resultMap.get("result_code");

				if (StringUtils.equals(tradeType, "APP") && StringUtils.equals(resultCode, "SUCCESS")) {
					Map<String, Object> modelMap = new TreeMap<>();
					modelMap.put("appId",AlipayConfig.APP_ID);
					//					modelMap.put("timeStamp", new Date().getTime());
					//					modelMap.put("nonceStr", DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30)));
					modelMap.put("prepayId", prepayId);
					modelMap.put("mch_id", AlipayConfig.MCH_ID);
					modelMap.put("orderId", entity.getId());
					//					modelMap.put("signType", "MD5");
					//					modelMap.put("paySign", generateSign(modelMap));
					//					modelMap.put("postPayUrl", getPostPayUrl(paymentPlugin, paymentTransaction));
					//					modelAndView.addAllObjects(modelMap);
					//					modelAndView.setViewName("net/shopxx/plugin/weixinPublicPayment/pay");
					resMap.put("code", "200");
					resMap.put("message", JSONObject.fromObject(modelMap).toString());
					return JSONObject.fromObject(resMap).toString();
				}else{
					resMap.put("code", "500");
					resMap.put("message", JSONObject.fromObject(resultMap).toString());
					return JSONObject.fromObject(resMap).toString();
				}
			}
		}

	}
	/**
	 * 
	 * @方法功能说明：微信APP支付结果通知
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	   @RequestMapping(value = "payNotifyUrl", produces = "application/json;charset=UTF-8")
	   @ResponseBody
	   public String notifyWeiXinPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
	        System.out.println("微信支付回调");
	        InputStream inStream = request.getInputStream();
	        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
	        byte[] buffer = new byte[1024];
	        int len = 0;
	        while ((len = inStream.read(buffer)) != -1) {
	            outSteam.write(buffer, 0, len);
	        }
	        String resultxml = new String(outSteam.toByteArray(), "utf-8");
	        System.out.println(resultxml);
	        Map<String, String> params = XmlUtils.toObject(resultxml, new TypeReference<Map<String, String>>() {});
	        outSteam.close();
	        inStream.close();
	        
	        
	        Map<String,String> return_data = new HashMap<String,String>();  
	        if (!WeixinConfig.isTenpaySign(params)) {
	        	System.out.println("===============微信验签失败==============");
	            // 支付失败
	        	return_data.put("return_code", "FAIL");  
	            return_data.put("return_msg", "return_code不正确");
	        	return WeixinConfig.GetMapToXML(return_data);
	        } else {
	            System.out.println("===============付款成功==============");
	            // ------------------------------
	            // 处理业务开始
	            // ------------------------------
	            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
	            // ------------------------------
				PayLogQo qo=new PayLogQo();
				qo.setSeachCoursesSeries(true);
				qo.setSeachUser(true);
	            String out_trade_no = String.valueOf(Long.parseLong(params.get("out_trade_no").split("O")[0]));
				qo.setPayLogId(Long.parseLong(out_trade_no));
				PayLog payLog=payLogService.queryUnique(qo);
				payLog.setStatus(2);
				payLog.setPaymentSuccessfulTime(new Date());

				payLogService.update(payLog);
				ServiceResultDto dto=andExpenditureRecorddService.capitalAddition(payLog);
				
	            String total_fee = params.get("total_fee");
	            double v = Double.valueOf(total_fee) / 100;
//	            String out_trade_no = String.valueOf(Long.parseLong(params.get("out_trade_no").split("O")[0]));
//				Date accountTime = DateUtil.stringtoDate(params.get("time_end"), "yyyyMMddHHmmss");
//				String ordertime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
				String totalAmount = String.valueOf(v);
				String appId = params.get("appid");
				String tradeNo = params.get("transaction_id");
			
				return_data.put("return_code", "SUCCESS");  
	            return_data.put("return_msg", "OK");  
				return WeixinConfig.GetMapToXML(return_data);
	        }

	   }
	/**
	 * 
	 * @方法功能说明：微信网页支付结果通知
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/payResult/{orderNo}")
	public ModelAndView payResult(@PathVariable Map<String, String> map, HttpServletRequest request, HttpServletResponse response){


		Map<String, Object> parameterMap = new TreeMap<>();
		parameterMap.put("appid", appid);
		parameterMap.put("mch_id", mch_id);
		parameterMap.put("out_trade_no", map.get("orderNo"));
		parameterMap.put("nonce_str", DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30)));
		parameterMap.put("sign", generateSign(parameterMap));
		String result = WebUtils.post(ORDER_QUERY_REQUEST_URL, XmlUtils.toXml(parameterMap));
		Map<String, String> resultMap = XmlUtils.toObject(result, new TypeReference<Map<String, String>>() {
		});
		if(StringUtils.equals(resultMap.get("return_code"), "SUCCESS") 
				&& StringUtils.equals(resultMap.get("result_code"), "SUCCESS") && 
				StringUtils.equals(resultMap.get("trade_state"), "SUCCESS")){
			System.out.println("成功");
			PayLogQo qo=new PayLogQo();
			qo.setSeachCoursesSeries(true);
			qo.setSeachUser(true);
			qo.setPayLogId(Long.parseLong(map.get("orderNo")));
			PayLog payLog=payLogService.queryUnique(qo);
			payLog.setStatus(2);
			payLog.setPaymentSuccessfulTime(new Date());

			payLogService.update(payLog);
			ServiceResultDto dto=andExpenditureRecorddService.capitalAddition(payLog);
			if(dto.getSuccess()) {
				System.out.println("成功");
			}

		}
		ModelAndView modelAndView = new ModelAndView();
		String xml="";
		try {
			xml = IOUtils.toString(request.getInputStream(), "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (StringUtils.isEmpty(xml)) {
			return null;
		}
		Map<String, String> resultMaps = XmlUtils.toObject(xml, new TypeReference<Map<String, String>>() {
		});

		if (StringUtils.equals(resultMaps.get("return_code"), "SUCCESS")) {
			modelAndView.addObject("message", "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
		}else{
			modelAndView.addObject("message", "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
		}
		return modelAndView;
	}

	/**
	 * 
	 * @方法功能说明：微信JS-SDK
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/signature")
	public String signature(String url) {
		Map<String, String> resMap=new HashMap<String, String>();


		if(WeixinConfig.getJsapi_ticketCreatTime()!=null){
			long diff = new Date().getTime() - WeixinConfig.getJsapi_ticketCreatTime().getTime();
			long s = diff/ (1000 * 60);
			if(s<100L){


				String uuid=UUID.randomUUID().toString().replaceAll("-", "");
				Date date=new Date();
				//								String string1="jsapi_ticket="+ticket+"&noncestr="+uuid+"&timestamp="+date.getTime()+"&url="+url;
				String sign = SignatureUtil.createSignature(date.getTime()/1000+"", uuid, WeixinConfig.getJsapi_ticket(), "http://"+url);
				Map<String, String> resMap1=new HashMap<String, String>();
				resMap1.put("timestamp", date.getTime()/1000+"");
				resMap1.put("noncestr",uuid);
				resMap1.put("sign", sign);
				resMap.put("code", "200");
				resMap.put("message", JSONObject.fromObject(resMap1).toString());
				return JSONObject.fromObject(resMap).toString();

			}else{
				Map<String, Object> parameterMap = new TreeMap<>();
				parameterMap.put("appid", appid);
				parameterMap.put("grant_type", "client_credential");
				parameterMap.put("secret", AppSecret);
				String result = WebUtils.get(access_token_url, parameterMap);
				com.alibaba.fastjson.JSONObject json=com.alibaba.fastjson.JSONObject.parseObject(result);
				if(StringUtils.isNotEmpty(json.getString("access_token"))){
					String access_token=json.getString("access_token");
					WeixinConfig.setAccess_token(access_token);
					WeixinConfig.setAccess_tokenCreatTime(new Date());
					Map<String, Object> parameterMap1 = new TreeMap<>();
					parameterMap1.put("access_token", access_token);
					parameterMap1.put("type", "jsapi");
					String result1 = WebUtils.get(jsapi_ticket_url, parameterMap1);
					com.alibaba.fastjson.JSONObject json1=com.alibaba.fastjson.JSONObject.parseObject(result1);
					if(StringUtils.equals(json1.getString("errmsg"), "ok")){
						String ticket=json1.getString("ticket");
						WeixinConfig.setJsapi_ticket(ticket);
						WeixinConfig.setJsapi_ticketCreatTime(new Date());
						String uuid=UUID.randomUUID().toString().replaceAll("-", "");
						Date date=new Date();
						//								String string1="jsapi_ticket="+ticket+"&noncestr="+uuid+"&timestamp="+date.getTime()+"&url="+url;
						String sign = SignatureUtil.createSignature(date.getTime()/1000+"", uuid, ticket, "http://"+url);
						Map<String, String> resMap1=new HashMap<String, String>();
						resMap1.put("timestamp", date.getTime()/1000+"");
						resMap1.put("noncestr",uuid);
						resMap1.put("sign", sign);
						resMap.put("code", "200");
						resMap.put("message", JSONObject.fromObject(resMap1).toString());
						return JSONObject.fromObject(resMap).toString();
					}else{
						resMap.put("code", "500");
						resMap.put("message", "获取jsapi_ticket失败!");
						return JSONObject.fromObject(resMap).toString();
					}

				}else{
					resMap.put("code", "500");
					resMap.put("message", "获取access_token失败!");
					return JSONObject.fromObject(resMap).toString();
				}
			}
		}else{
			Map<String, Object> parameterMap = new TreeMap<>();
			parameterMap.put("appid", appid);
			parameterMap.put("grant_type", "client_credential");
			parameterMap.put("secret", AppSecret);
			String result = WebUtils.get(access_token_url, parameterMap);
			com.alibaba.fastjson.JSONObject json=com.alibaba.fastjson.JSONObject.parseObject(result);
			if(StringUtils.isNotEmpty(json.getString("access_token"))){
				String access_token=json.getString("access_token");
				WeixinConfig.setAccess_token(access_token);
				WeixinConfig.setAccess_tokenCreatTime(new Date());
				Map<String, Object> parameterMap1 = new TreeMap<>();
				parameterMap1.put("access_token", access_token);
				parameterMap1.put("type", "jsapi");
				String result1 = WebUtils.get(jsapi_ticket_url, parameterMap1);
				com.alibaba.fastjson.JSONObject json1=com.alibaba.fastjson.JSONObject.parseObject(result1);
				if(StringUtils.equals(json1.getString("errmsg"), "ok")){
					String ticket=json1.getString("ticket");
					WeixinConfig.setJsapi_ticket(ticket);
					WeixinConfig.setJsapi_ticketCreatTime(new Date());
					String uuid=UUID.randomUUID().toString().replaceAll("-", "");
					Date date=new Date();
					//							String string1="jsapi_ticket="+ticket+"&noncestr="+uuid+"&timestamp="+date.getTime()+"&url="+url;
					String sign = SignatureUtil.createSignature(date.getTime()/1000+"", uuid, ticket, "http://"+url);
					Map<String, String> resMap1=new HashMap<String, String>();
					resMap1.put("timestamp", date.getTime()/1000+"");
					resMap1.put("noncestr",uuid);
					resMap1.put("sign", sign);
					resMap.put("code", "200");
					resMap.put("message", JSONObject.fromObject(resMap1).toString());
					return JSONObject.fromObject(resMap).toString();
				}else{
					resMap.put("code", "500");
					resMap.put("message", "获取jsapi_ticket失败!");
					return JSONObject.fromObject(resMap).toString();
				}

			}else{
				resMap.put("code", "500");
				resMap.put("message", "获取access_token失败!");
				return JSONObject.fromObject(resMap).toString();
			}
		}






	}
	//查询订单
	@ResponseBody
	@RequestMapping(value = "/searchOrder")
	public String payResult(@RequestParam(value="token", required=true)String  token,HttpServletRequest request, HttpServletResponse response,String orderId){
		Map<String, Object> resMap=new HashMap<String, Object>();
		AdminSession adminSession=new AdminSession();
		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession==null) {
			resMap.put("code", "406");
			resMap.put("message", "不存在此账号！");
			return JSONObject.fromObject(resMap).toString();
		}else {
			adminSession.getLoginName();
			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user==null) {
				resMap.put("code", "406");
				resMap.put("message", "未登录!");
				return JSONObject.fromObject(resMap).toString();
			}else {
				PayLogQo qo=new PayLogQo();
				//				qo.setSeachCoursesSeries(true);
				//				qo.setSeachUser(true);
				qo.setPayLogId(Long.parseLong(orderId));
				PayLog payLog=payLogService.queryUnique(qo);
				if(payLog.getStatus()==1){

					Map<String, Object> parameterMap = new TreeMap<>();
					parameterMap.put("appid", appid);
					parameterMap.put("mch_id", mch_id);
					parameterMap.put("out_trade_no",orderId);
					parameterMap.put("nonce_str", DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30)));
					parameterMap.put("sign", generateSign(parameterMap));
					String result = WebUtils.post(ORDER_QUERY_REQUEST_URL, XmlUtils.toXml(parameterMap));
					Map<String, String> resultMap = XmlUtils.toObject(result, new TypeReference<Map<String, String>>() {
					});
					String return_code = resultMap.get("return_code");
					if (StringUtils.equals(return_code, "SUCCESS")) {
						String result_code = resultMap.get("result_code");
						String trade_state = resultMap.get("trade_state");
						if (StringUtils.equals(result_code, "SUCCESS")&&StringUtils.equals(trade_state, "SUCCESS")) {
							payLog.setStatus(2);
							payLog.setPaymentSuccessfulTime(new Date());

							payLogService.update(payLog);
						}
					}
					resMap.put("code", "200");
					resMap.put("message", payLog);
				}else{
					resMap.put("code", "200");
					resMap.put("message", payLog);
				}


				return JSONObject.fromObject(resMap).toString();
			}
		}


	}
	//查询订单列表
	@ResponseBody
	@RequestMapping(value = "/orderList")
	public String orderList(@RequestParam(value="token", required=true)String  token,HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> resMap=new HashMap<String, Object>();
		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession==null) {
			resMap.put("code", "406");
			resMap.put("message", "不存在此账号！");
			return JSONObject.fromObject(resMap).toString();
		}else {
			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user==null) {
				resMap.put("code", "406");
				resMap.put("message", "未登录!");
				return JSONObject.fromObject(resMap).toString();
			}else {
				PayLogQo qo=new PayLogQo();
				qo.setUser(user.getId());
				qo.setStatus(2);
				qo.setSeachCoursesSeries(true);
				Pagination pagination = new Pagination();
				pagination.setPageSize(10);
				pagination.setCondition(qo);
				pagination = payLogService.queryPagination(pagination);
				SysProperties sysProperties=SysProperties.getInstance();
				String imagePath=sysProperties.get("imagePath");
				SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				for(PayLog payLog:(List<PayLog>)pagination.getList()) {
					payLog.getCoursesSeries().setCover(imagePath+"/img/"+payLog.getCoursesSeries().getCover());
					payLog.getCoursesSeries().setTotalDetails("");
					payLog.setParameters("");
					payLog.setCreateDate(format1.format(payLog.getCreateTime()));
				}
				resMap.put("code", "200");
				resMap.put("message", pagination);
				return JSONObject.fromObject(resMap).toString();
			}
		}

	}
	/**
	 * 创建商户订单  请求支付宝
	 * @param amount
	 * @param random
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getsign")
	public String getsign(@RequestParam(value="token", required=true)String  token,String coursesSeriesId){
		AdminSession adminSession=new AdminSession();
		Map<String, String> resMap=new HashMap<String, String>();
		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession==null) {
			resMap.put("code", "406");
			resMap.put("message", "不存在此账号！");
			return JSONObject.fromObject(resMap).toString();
		}else {
			adminSession.getLoginName();
			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user==null) {
				resMap.put("code", "406");
				resMap.put("message", "未登录!");
				return JSONObject.fromObject(resMap).toString();
			}else {

				CoursesSeries coursesSeries=coursesSeriesService.get(Long.parseLong(coursesSeriesId));
				if(coursesSeries==null){
					resMap.put("code", "500");
					resMap.put("message", "课程为空!");
					return JSONObject.fromObject(resMap).toString();
				}
				PayLogQo payLogQo=new PayLogQo();
				payLogQo.setUser(user.getId());
				payLogQo.setCoursesSeries(Long.parseLong(coursesSeriesId));
				payLogQo.setStatus(2);
				PayLog payLog=payLogService.queryUnique(payLogQo);
				if(payLog!=null){
					resMap.put("code", "500");
					resMap.put("message", "课程已购买!");
					return JSONObject.fromObject(resMap).toString();
				}
				
				PayLog entity=new PayLog();
//				entity.setParameters(JSONObject.fromObject(parameterMap).toString());
				entity.setPayType(2);
				entity.setStatus(1);
				entity.setMoney(coursesSeries.getPrice());
				entity.setCoursesSeries(coursesSeries);
				entity.setCreateTime(new Date());
				entity.setUser(user);
				entity=payLogService.save(entity);
				//实例化客户端
				AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATE, 
						AlipayConfig.APPID,
						AlipayConfig.APP_PRIVATE_KEY, 
						"json", AlipayConfig.CHARSET, 
						AlipayConfig.ALIPAY_PUBLIC_KEY, 
						"RSA2");
//				 if (Double.valueOf(coursesSeries) <= 0){ // 一些必要的验证，防止抓包恶意修改支付金额
//					 return null;
//			     }
				 //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		        model.setBody("课程订单");
		        model.setSubject(coursesSeries.getTotalTitle());
		        model.setOutTradeNo(entity.getId().toString());  //订单号
		        model.setTimeoutExpress("30m");  // 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
		        model.setTotalAmount(String.valueOf(coursesSeries.getPrice()/100D)); // 订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]这里调试每次支付1分钱，在项目上线前应将此处改为订单的总金额
		        model.setProductCode("QUICK_MSECURITY_PAY");// 销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
		        request.setBizModel(model);
		        // 设置后台异步通知的地址，在手机端支付成功后支付宝会通知后台，手机端的真实支付结果依赖于此地址
		        request.setNotifyUrl("http://www.baizeyikao.cn/webMobile/user/aliPay_notify");
		        AlipayTradeAppPayResponse response = new AlipayTradeAppPayResponse();
		        try {
		            //这里和普通的接口调用不同，使用的是sdkExecute
		            response = alipayClient.sdkExecute(request);
		            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
				resMap.put("code", "200");
				resMap.put("message", response.getBody());
				return JSONObject.fromObject(resMap).toString();
			}
		}


	}

	/**
	 * 支付宝支付成功后.异步请求该接口
	 * @param requestParams
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/aliPay_notify")
	public String aliPay_notify(HttpServletRequest request){
	       Map<String, String> params = convertRequestParamsToMap(request); // 将异步通知中收到的待验证所有参数都存放到map中
	        String paramsJson = JSON.toJSONString(params);
	        System.out.println("支付宝回调，{}"+paramsJson);

	        try {
//	            AlipayConfig alipayConfig = new AlipayConfig();// 支付宝配置
	            // 调用SDK验证签名
	            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY,
	            		AlipayConfig.CHARSET, "RSA2");
	            if (signVerified) {
	            	System.out.println("支付宝回调签名认证成功");
	                // 按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success，校验失败返回failure
	                this.check(params);
	                // 另起线程处理业务
	                executorService.execute(new Runnable() {
	                    @Override
	                    public void run() {
	                    	
	                    	 if("TRADE_SUCCESS".equals(params.get("trade_status"))){
	                           //付款金额
	                           String amount = params.get("buyer_pay_amount");
	                           //商户订单号
	                           String out_trade_no = params.get("out_trade_no");
	                           //支付宝交易号
	                           String trade_no = params.get("trade_no");

	               			System.out.println("成功"+amount+"*"+out_trade_no+"*"+trade_no+"*");
	               			PayLogQo qo=new PayLogQo();
	               			qo.setSeachCoursesSeries(true);
	               			qo.setSeachUser(true);
	               			qo.setPayLogId(Long.parseLong(out_trade_no));
	               			PayLog payLog=payLogService.queryUnique(qo);
	               			payLog.setStatus(2);
	               			
	               			payLog.setPaymentSuccessfulTime(new Date());
	       
	               			payLogService.update(payLog);
	               			ServiceResultDto dto=andExpenditureRecorddService.capitalAddition(payLog);
	               			if(dto.getSuccess()) {
	               				System.out.println("成功");
	               			}
	                    	 }

	                    }
	                });
	                // 如果签名验证正确，立即返回success，后续业务另起线程单独处理
	                // 业务处理失败，可查看日志进行补偿，跟支付宝已经没多大关系。
	                return "success";
	            } else {
	            	System.out.println("支付宝回调签名认证失败，signVerified=false, paramsJson:{}"+ paramsJson);
	                return "failure";
	            }
	        } catch (AlipayApiException e) {
	        	System.out.println("支付宝回调签名认证失败,paramsJson:{},errorMsg:{}"+ paramsJson+ e.getMessage());
	            return "failure";
	        }

 
//        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
//            String name = (String) iter.next();
//            String[] values = (String[])requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                            : valueStr + values[i] + ",";
//            }
//          //乱码解决，这段代码在出现乱码时使用。
//          //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//          params.put(name, valueStr);
//         }
//        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
//        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
//        try {
//            boolean flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
//            if(flag){
//                if("TRADE_SUCCESS".equals(params.get("trade_status"))){
//                    //付款金额
//                    String amount = params.get("buyer_pay_amount");
//                    //商户订单号
//                    String out_trade_no = params.get("out_trade_no");
//                    //支付宝交易号
//                    String trade_no = params.get("trade_no");
//                    //附加数据
//                    String passback_params = URLDecoder.decode(params.get("passback_params"));
//        			System.out.println("成功"+amount+"*"+out_trade_no+"*"+trade_no+"*"+passback_params);
//        			PayLogQo qo=new PayLogQo();
//        			qo.setSeachCoursesSeries(true);
//        			qo.setSeachUser(true);
//        			qo.setPayLogId(Long.parseLong(out_trade_no));
//        			PayLog payLog=payLogService.queryUnique(qo);
//        			payLog.setStatus(2);
//        			payLog.setPaymentSuccessfulTime(new Date());
//
//        			payLogService.update(payLog);
//        			ServiceResultDto dto=andExpenditureRecorddService.capitalAddition(payLog);
//        			if(dto.getSuccess()) {
//        				System.out.println("成功");
//        			}
//                }
//            }
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//      return "success";
    }
	
	   /**
     * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
     * 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
     * 3、校验通知中的seller_id（或者seller_email)是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email），
     * 4、验证app_id是否为该商户本身。上述1、2、3、4有任何一个验证不通过，则表明本次通知是异常通知，务必忽略。
     * 在上述验证通过后商户必须根据支付宝不同类型的业务通知，正确的进行不同的业务处理，并且过滤重复的通知结果数据。
     * 在支付宝的业务通知中，只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时，支付宝才会认定为买家付款成功。
     * 
     * @param params
     * @throws AlipayApiException
     */
    private void check(Map<String, String> params) throws AlipayApiException {      
        String outTradeNo = params.get("out_trade_no");

        // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		PayLogQo qo=new PayLogQo();
		qo.setSeachCoursesSeries(true);
		qo.setSeachUser(true);
		qo.setPayLogId(Long.parseLong(outTradeNo));
		PayLog payLog=payLogService.queryUnique(qo);
//        Order order = getOrderByOutTradeNo(outTradeNo); // 这个方法自己实现
        if (payLog == null) {
            throw new AlipayApiException("out_trade_no错误");
        }       

        // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        long total_amount = new BigDecimal(params.get("total_amount")).multiply(new BigDecimal(100)).longValue();     
		
        if (total_amount != payLog.getCoursesSeries().getPrice().longValue()) {
            throw new AlipayApiException("error total_amount");
        }

        // 3、校验通知中的seller_id（或者seller_email)是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email），
        // 第三步可根据实际情况省略

        // 4、验证app_id是否为该商户本身。
        if (!params.get("app_id").equals(AlipayConfig.APPID)) {
            throw new AlipayApiException("app_id不一致");
        }
    }

	
	
	
	  // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

	/**
     * @param totalAmount    支付金额
     * @param description    描述
     * @param request
     * @return
     */
//    @RequestMapping(value = "/wxpay")
//    @ResponseBody    
//    public String wxpay(HttpServletRequest request) {
//    	HashMap<String, Object> result = new HashMap<>();
//        Long userId = new Long(1);//baseController.getUserId();
//       
//        BigDecimal totalAmount = new BigDecimal(request.getParameter("totalPrice"));
//        String trade_no = "";
//        String description="";
//		try {
//			trade_no = new String(request.getParameter("orderNum").getBytes("ISO-8859-1"),"UTF-8");
//			description = request.getParameter("description");
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//        String openId = "";
//        
//        Map<String, String> map = weixinPrePay(trade_no,totalAmount,description,openId,request);  
//        SortedMap<String, Object> finalpackage = new TreeMap<String, Object>();
//        //应用ID
//        finalpackage.put("appid", AlipayConfig.APP_ID)/*PayCommonUtil.APPID*/);
//        //商户号
//        finalpackage.put("partnerid", AlipayConfig.MCH_ID);
//        Long time = (System.currentTimeMillis() / 1000);
//        //时间戳
//        finalpackage.put("timestamp", time.toString());
//        //随机字符串
//        finalpackage.put("noncestr", map.get("nonce_str"));
//        //预支付交易会话ID
//        finalpackage.put("prepayid", map.get("prepay_id"));
//        //扩展字段
//        finalpackage.put("package", "Sign=WXPay");
//        
//        WeiXinPrePay prePay = new WeiXinPrePay();
//        prePay.setAppId(ConfigManager.getInstance().getConfigItem("WXAppID"));
//        prePay.setMchId(ConfigManager.getInstance().getConfigItem("MCH_ID"));
//        prePay.setTimeStamp(time.toString());
//        prePay.setNonceStr(map.get("nonce_str"));
//        prePay.setPrepayId(map.get("prepay_id"));
//        prePay.setSignType("MD5");
//        prePay.setPaySign(sign);
//        result.setData(prePay);
//        result.setStateCode(GeneralConstant.SUCCESS);
//        result.setDesc("微信支付加载成功");
//        
//        return result;
//    } 
 
	
	/**
     * 统一下单 
     * 应用场景：商户系统先调用该接口在微信支付服务后台生成预支付交易单，返回正确的预支付交易回话标识后再在APP里面调起支付。
     * @param trade_no
     * @param totalAmount
     * @param description
     * @param openid
     * @param sym
     * @param request
     * @return
     */
//    @SuppressWarnings("unchecked")
//    public Map<String, String> weixinPrePay(String trade_no,BigDecimal totalAmount,  
//            String description, String openid, HttpServletRequest request) { 
//        SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();  
//        parameterMap.put("appid",  AlipayConfig.APP_ID);  //应用appid 
//        parameterMap.put("mch_id",  AlipayConfig.MCH_ID)/*PayCommonUtil.MCH_ID*/);  //商户号
//        //parameterMap.put("device_info", "WEB");
//        parameterMap.put("nonce_str", randomString);  
//        parameterMap.put("body", description);
//        parameterMap.put("out_trade_no", trade_no);
//        parameterMap.put("fee_type", "CNY");  
//        System.out.println("jiner");  
//        BigDecimal total = totalAmount.multiply(new BigDecimal(100));  //接口中参数支付金额单位为【分】，参数值不能带小数，所以乘以100
//        java.text.DecimalFormat df=new java.text.DecimalFormat("0");  
//        parameterMap.put("total_fee", df.format(total));  
//        System.out.println("jiner2");  
//        parameterMap.put("spbill_create_ip", PayCommonUtil.getRemoteHost(request));  
//        parameterMap.put("notify_url", wxnotify);
//        parameterMap.put("trade_type", "APP");//"JSAPI"
//        //trade_type为JSAPI是 openid为必填项
//        //parameterMap.put("openid", openid);
//        System.out.println("");  
//        String sign = PayCommonUtil.createSign("UTF-8", parameterMap); 
//        System.out.println("jiner2");  
//        parameterMap.put("sign", sign);  
//        String requestXML = PayCommonUtil.getRequestXml(parameterMap);  
//        System.out.println(requestXML);  
//        String result = PayCommonUtil.httpsRequest(  
//                "https://api.mch.weixin.qq.com/pay/unifiedorder", "POST",  
//                requestXML);  
//        System.out.println(result);  
//        Map<String, String> map = null;  
//        try {  
//            map = PayCommonUtil.doXMLParse(result);  
//        } catch (JDOMException e) {  
//            // TODO Auto-generated catch block  
//            e.printStackTrace();  
//        } catch (IOException e) {  
//            // TODO Auto-generated catch block  
//            e.printStackTrace();  
//        }  
//        return map;        
//    }

    
    
	//下载微信语音
	//	@ResponseBody
	//	@RequestMapping(value = "/saveAmr")
	//	public String saveAmr(@RequestParam(value="token", required=true)String  token,HttpServletRequest request, HttpServletResponse response,String id){
	//		Map<String, Object> resMap=new HashMap<String, Object>();
	//		AdminSessionQo adminSessionQo=new AdminSessionQo();
	//		adminSessionQo.setToken(token);
	//		AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
	//		if(adminSession==null) {
	//			resMap.put("code", "406");
	//			resMap.put("message", "不存在此账号！");
	//			return JSONObject.fromObject(resMap).toString();
	//		}else {
	//			UserQo userQo=new UserQo();
	//			userQo.setUserName(adminSession.getLoginName());
	//			User user= userService.queryUnique(userQo);
	//			if(user==null) {
	//				resMap.put("code", "406");
	//				resMap.put("message", "未登录!");
	//				return JSONObject.fromObject(resMap).toString();
	//			}else {
	//				String accessToken="";
	//				SysProperties sysProperties=SysProperties.getInstance();
	//				String imagePath=sysProperties.get("VoiceFile")+"/"+user.getId()+"/";
	//				String dateName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
	//				if(WeixinConfig.getAccess_tokenCreatTime()!=null){
	//				    long diff = new Date().getTime() - WeixinConfig.getAccess_tokenCreatTime().getTime();
	//				    long s = diff/ (1000 * 60);
	//				    if(s<100L){
	//				    	accessToken=WeixinConfig.getAccess_token();
	//
	//						try {
	//							String code=saveImageToDisk(accessToken, id, dateName, imagePath);
	//							if("200".equals(code)){
	//								resMap.put("code", "200");
	//								resMap.put("message", "ok");
	//								return JSONObject.fromObject(resMap).toString();
	//							}else{
	//								resMap.put("code", "500");
	//								resMap.put("message", "error");
	//								return JSONObject.fromObject(resMap).toString();
	//							}
	//						} catch (Exception e) {
	//							// TODO Auto-generated catch block
	//							e.printStackTrace();
	//							resMap.put("code", "500");
	//							resMap.put("message", "error");
	//							return JSONObject.fromObject(resMap).toString();
	//						}
	//	
	//				    }else{
	//						Map<String, Object> parameterMap = new TreeMap<>();
	//						parameterMap.put("appid", appid);
	//						parameterMap.put("grant_type", "client_credential");
	//						parameterMap.put("secret", AppSecret);
	//						String result = WebUtils.get(access_token_url, parameterMap);
	//						com.alibaba.fastjson.JSONObject json=com.alibaba.fastjson.JSONObject.parseObject(result);
	//						if(StringUtils.isNotEmpty(json.getString("access_token"))){
	//							accessToken=json.getString("access_token");
	//
	//							try {
	//								String code=saveImageToDisk(accessToken, id, dateName, imagePath);
	//								if("200".equals(code)){
	//									resMap.put("code", "200");
	//									resMap.put("message", "ok");
	//									return JSONObject.fromObject(resMap).toString();
	//								}else{
	//									resMap.put("code", "500");
	//									resMap.put("message", "error");
	//									return JSONObject.fromObject(resMap).toString();
	//								}
	//							} catch (Exception e) {
	//								// TODO Auto-generated catch block
	//								e.printStackTrace();
	//								resMap.put("code", "500");
	//								resMap.put("message", "error");
	//								return JSONObject.fromObject(resMap).toString();
	//							}
	//
	//						}else{
	//							resMap.put("code", "500");
	//							resMap.put("message", "获取accessToken失败");
	//							return JSONObject.fromObject(resMap).toString();
	//						}
	//				    }
	//				}else{
	//					Map<String, Object> parameterMap = new TreeMap<>();
	//					parameterMap.put("appid", appid);
	//					parameterMap.put("grant_type", "client_credential");
	//					parameterMap.put("secret", AppSecret);
	//					String result = WebUtils.get(access_token_url, parameterMap);
	//					com.alibaba.fastjson.JSONObject json=com.alibaba.fastjson.JSONObject.parseObject(result);
	//					if(StringUtils.isNotEmpty(json.getString("access_token"))){
	//						accessToken=json.getString("access_token");
	//
	//						try {
	//							String code=saveImageToDisk(accessToken, id, dateName, imagePath);
	//							if("200".equals(code)){
	//								resMap.put("code", "200");
	//								resMap.put("message", "ok");
	//								return JSONObject.fromObject(resMap).toString();
	//							}else{
	//								resMap.put("code", "500");
	//								resMap.put("message", "error");
	//								return JSONObject.fromObject(resMap).toString();
	//							}
	//						} catch (Exception e) {
	//							// TODO Auto-generated catch block
	//							e.printStackTrace();
	//							resMap.put("code", "500");
	//							resMap.put("message", "error");
	//							return JSONObject.fromObject(resMap).toString();
	//						}
	//
	//					}else{
	//						resMap.put("code", "500");
	//						resMap.put("message", "获取accessToken失败");
	//						return JSONObject.fromObject(resMap).toString();
	//					}
	//				}
	//
	//				
	//				
	//			}
	//		}
	//	}

	/**
	 * 
	 * @Title: changeToMp3
	 * @Description: amr转mp3
	 * @param sourcePath 被转文件地址
	 * @param targetPath 转换后保存地址
	 */
	//public static String changeAmrToMp3(String sourcePath, String targetPath) throws IllegalArgumentException, EncoderException {
	//			//获取文件地址。追踪到软件所在文件夹ji
	//			SysProperties sysProperties=SysProperties.getInstance();
	//			String webroot=sysProperties.get("ffmpeg_path");
	//
	//
	//			Runtime run = null;
	//			try {
	//				run = Runtime.getRuntime();
	//				long start = System.currentTimeMillis();
	//				System.out.println(new File(webroot).getAbsolutePath());
	//				// 执行ffmpeg.exe,前面是ffmpeg.exe的地址，中间是需要转换的文件地址，后面是转换后的文件地址。-i是转  换方式，意思是可编码解码，mp3编码方式采用的是libmp3lame
	//				Process p = run.exec(new File(webroot).getAbsolutePath() + " -i " + sourcePath
	//						+ " -acodec libmp3lame " + targetPath);
	//		        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
	//                String line = null;
	//             //   StringBuilder result = new StringBuilder();
	//                while ((line = br.readLine()) != null) {
	//                    System.out.println(line);
	//                    }
	//				// 释放进程
	////                p.waitFor(2, TimeUnit.SECONDS);
	////				p.getOutputStream().close();
	////				p.getInputStream().close();
	////				p.getErrorStream().close();
	////				p.destroy();
	//				long end = System.currentTimeMillis();
	//				System.out.println(sourcePath + " convert success, costs:" + (end - start) + "ms");
	//				return "200";
	//			} catch (Exception e) {
	//				e.printStackTrace();
	//				return "400";
	//			} finally {
	//				// run调用lame解码器最后释放内存
	//				run.freeMemory();
	//			}
	//}



	/**
	 * 
	 * 获取下载音频信
	 * 
	 * 
	 * 
	 * @param mediaId
	 * 
	 *            文件的id
	 * 
	 * @throws Exception
	 */

	//	public static String saveImageToDisk(String accessToken, String mediaId, String picName, String picPath)
	//			throws Exception {
	//		InputStream inputStream = getInputStream(accessToken, mediaId);
	//		byte[] data = new byte[10240];
	//		int len = 0;
	//		FileOutputStream fileOutputStream = null;
	//		try {
	//			File dir = new File(picPath);
	//			if (!dir.exists()) {
	//				dir.mkdirs();
	//			}
	//			fileOutputStream = new FileOutputStream(picPath+picName+".amr");
	//			while ((len = inputStream.read(data)) != -1) {
	//				fileOutputStream.write(data, 0, len);
	//			}
	//			String code=changeAmrToMp3(picPath+picName+".amr", picPath+picName+".mp3");
	//			if("200".equals(code)){
	//				return "200";
	//			}else{
	//				return "500";
	//			}
	//			
	//		} catch (IOException e) {
	//			
	//			e.printStackTrace();
	//			return "500";
	//		} finally {
	//			if (inputStream != null) {
	//				try {
	//					inputStream.close();
	//				} catch (IOException e) {
	//					e.printStackTrace();
	//				}
	//			}
	//			if (fileOutputStream != null) {
	//				try {
	//					fileOutputStream.close();
	//				} catch (IOException e) {
	//					e.printStackTrace();
	//				}
	//			}
	//		}
	//
	//	}
	/**
	 * 
	 * 根据文件id下载文件
	 * 
	 * 
	 * 
	 * @param mediaId
	 * 
	 *            媒体id
	 * 
	 * @throws Exception
	 */

	public static InputStream getInputStream(String accessToken, String mediaId) {
		InputStream is = null;
		String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
				+ accessToken + "&media_id=" + mediaId;
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet
					.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			// 获取文件转化为byte流
			is = http.getInputStream();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return is;
	}



	/**
	 * 生成签名
	 * 
	 * @param parameterMap
	 *            参数
	 * @return 签名
	 */
	private String generateSign(Map<String, ?> parameterMap) {
		return StringUtils.upperCase(DigestUtils.md5Hex(joinKeyValue(new TreeMap<>(parameterMap), null, "&key=" + ApiKey, "&", true)));
	}
	/**
	 * 连接Map键值对
	 * 
	 * @param map
	 *            Map
	 * @param prefix
	 *            前缀
	 * @param suffix
	 *            后缀
	 * @param separator
	 *            连接符
	 * @param ignoreEmptyValue
	 *            忽略空值
	 * @param ignoreKeys
	 *            忽略Key
	 * @return 字符串
	 */
	protected String joinKeyValue(Map<String, Object> map, String prefix, String suffix, String separator, boolean ignoreEmptyValue, String... ignoreKeys) {
		List<String> list = new ArrayList<>();
		if (map != null) {
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				String key = entry.getKey();
				String value = ConvertUtils.convert(entry.getValue());
				if (StringUtils.isNotEmpty(key) && !ArrayUtils.contains(ignoreKeys, key) && (!ignoreEmptyValue || StringUtils.isNotEmpty(value))) {
					list.add(key + "=" + (value != null ? value : ""));
				}
			}
		}
		return (prefix != null ? prefix : "") + StringUtils.join(list, separator) + (suffix != null ? suffix : "");
	}
	/**
	 * 获取OpenID
	 * 
	 * @param code
	 *            code值
	 * @return OpenID
	 */
	private String getOpenId(String code) {
		try {
			OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
			TokenRequestBuilder tokenRequestBuilder = OAuthClientRequest.tokenLocation(OPEN_ID_REQUEST_URL);
			tokenRequestBuilder.setParameter("appid", appid);
			tokenRequestBuilder.setParameter("secret", AppSecret);
			tokenRequestBuilder.setCode(code);
			tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
			OAuthClientRequest accessTokenRequest = tokenRequestBuilder.buildQueryMessage();
			OAuthJSONAccessTokenResponse authJSONAccessTokenResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.GET);
			return authJSONAccessTokenResponse.getParam("openid");
		} catch (OAuthSystemException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (OAuthProblemException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}


	//code验证码,phoneNumber手机号码,temType模板.1为注册验证码,2为重置密码验证码
	public static SendSmsResponse sendSms(String code,String phoneNumber,Integer temType){

		String TemplateCode=TemplateCode1;
		if(temType!=null&&temType==2) {
			TemplateCode=TemplateCode2;
		}
		//可自助调整超时时间
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");

		//初始化acsClient,暂不支持region化
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		try {
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		} catch (ClientException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		IAcsClient acsClient = new DefaultAcsClient(profile);

		//组装请求对象-具体描述见控制台-文档部分内容
		SendSmsRequest request = new SendSmsRequest();
		//必填:待发送手机号
		request.setPhoneNumbers(phoneNumber);
		//必填:短信签名-可在短信控制台中找到
		request.setSignName("白泽艺考");
		//必填:短信模板-可在短信控制台中找到
		request.setTemplateCode("SMS_147416051");
		//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		request.setTemplateParam("{\"code\":\""+code+"\"}");

		//选填-上行短信扩展码(无特殊需求用户请忽略此字段)
		//request.setSmsUpExtendCode("90997");

		//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		request.setOutId("yourOutId");

		//hint 此处可能会抛出异常，注意catch
		SendSmsResponse sendSmsResponse=new SendSmsResponse();
		try {
			sendSmsResponse = acsClient.getAcsResponse(request);
		} catch (ServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return sendSmsResponse;
	}

	/**	 * 产生6位随机数(000000-999999)	 * 	 * @return 6位随机数	 */	
	public static String getFourRandom() {
		Random random = new Random();
		String fourRandom = random.nextInt(1000000) + "";	
		int randLength = fourRandom.length();
		if (randLength < 6) {
			for (int i = 1; i <= 6 - randLength; i++)
				fourRandom = "0" + fourRandom;
		}
		return fourRandom;	
	}
	public boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((1)+\\d{10})$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}



}
